﻿using MediatR;
using SmartApplication.Api.Applient.Command.Source;
using SmartApplication.ApiCode;
using SmartApplication.Domain.Entity;
using SmartApplication.Infrastructure.Instrument;

namespace SmartApplication.Api.Applient.CommandHandler.Source
{
    public class DeleteSourceHandler : IRequestHandler<DeleteSourceCommand, ApiResult<int>>
    {
        public DeleteSourceHandler(IBaseRepository<SourceModel> sourceRepository)
        {
            SourceRepository = sourceRepository;
        }

        public IBaseRepository<SourceModel> SourceRepository { get; }

        /// <summary>
        /// 溯源信息逻辑删除
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<ApiResult<int>> Handle(DeleteSourceCommand request, CancellationToken cancellationToken)
        {
            var res=new ApiResult<int>();

            var source = await SourceRepository.GetValueAsync(request.Id);

            if (source == null)
            {
                res.Code = EnumCode.Fail;
                res.Message = "没有查找到您所需要的数据";
                return res;
            }

            source.IsDeleted = true;

            var del=await SourceRepository.UpdateAsync(source);
            if(del>0)
            {
                res.Code=EnumCode.Success;
                res.Message = "逻辑删除成功";
                res.Data = del;
                return res;
            }
            else
            {
                res.Code = EnumCode.Fail;
                res.Message = "逻辑删除失败";
                res.Data = del;
                return res;
            }
        }
    }
}
